﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Journal.Common.Objects;

namespace Journal.Common.WebApplication
{
    public class BaseApplication : HttpApplication
    {
        /*public static readonly ILog Logger = LogManager.GetLogger(typeof(PlatformWebApplication));*/

        protected static readonly IList<string> IgnoreExtentions = new List<string>
                                                                       {"js", "css", "png", "gif", "jpg", "txt", "ico"};

        protected virtual void Application_Start()
        {
            RegisterIgnoreRoutes(RouteTable.Routes);
            AreaRegistration.RegisterAllAreas();
        }

        protected virtual void RegisterIgnoreRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{*resource}",
                               new
                                   {
                                       resource =
                                   string.Format(@".*\.({0})(/.*)?", string.Join("|", IgnoreExtentions.ToArray()))
                                   });
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        }

        /*        protected virtual void Application_Error(object sender, EventArgs e)
                {
                    Logger.Error(string.Format("Error at application at url '{0}': \n{1}", HttpContext.Current.Request.RawUrl, HttpContext.Current.Server.GetLastError()));
                }*/

       

        public static SystemUser GetLoggedUser()
        {
            return HttpContext.Current.User as SystemUser;
        }

        protected virtual void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (IgnoreExtentions.All(ext => !Request.RawUrl.EndsWith("." + ext)) && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var identity = HttpContext.Current.User.Identity as FormsIdentity;
                if (identity != null)
                {
                    var ticket = identity.Ticket;
                    var roles = ticket.UserData.Split(',');
                    var userId = int.Parse(identity.Name.Split('/').First());
                    var login = identity.Name.Split('/')[1];
                    HttpContext.Current.User = new SystemUser(identity, roles, login, userId);
                }
            }
        }
    }
}